package main

import (
	"context"
	"grpcPrimary/api"
	"grpcPrimary/pb"
	"log"
	"net"
	"time"

	"google.golang.org/grpc"
)

const (
	port = ":8080"
)

func orderUnaryServerInterceptor(
	ctx context.Context,
	req interface{},
	info *grpc.UnaryServerInfo,
	handler grpc.UnaryHandler) (interface{}, error) {
	//前置处理
	log.Println("====== [Server Interceptor] ", info.FullMethod)

	//继续正常执行逻辑
	m, err := handler(ctx, req)

	//后置处理
	log.Printf(" Post Proc Message : %s", m)
	return m, err
}

// 服务器端流拦截器
// wrappedStream包装签入的grpc.ServerStream
// 并拦截对RecvMsg函数和SendMsg函数的调用
type wrappedStream struct {
	grpc.ServerStream
}

func (w *wrappedStream) RecvMsg(m interface{}) error {
	log.Printf("====== [Server Stream Interceptor Wrapper]"+
		"Receive a message (Type: %T) at %s", m, time.Now().Format(time.RFC3339))
	return w.ServerStream.RecvMsg(m)
}

func (w *wrappedStream) SendMsg(m interface{}) error {
	log.Printf("====== [Server Stream Interceptor Wrapper]"+
		"Send a message (Type: %T) at %s", m, time.Now().Format(time.RFC3339))
	return w.ServerStream.SendMsg(m)
}

func newWrappedStream(s grpc.ServerStream) grpc.ServerStream {
	return &wrappedStream{s}
}

func orderServerStreamInterceptor(
	srv interface{},
	ss grpc.ServerStream,
	info *grpc.StreamServerInfo,
	handler grpc.StreamHandler,
) error {
	log.Println("====== [Server Stream Interceptor]" + info.FullMethod)
	err := handler(srv, newWrappedStream(ss))
	if err != nil {
		log.Printf("RPC failed with error %v", err)
	}
	return err
}

func main() {
	lis, _ := net.Listen("tcp", port)
	s := grpc.NewServer(
		grpc.UnaryInterceptor(orderUnaryServerInterceptor),
		grpc.StreamInterceptor(orderServerStreamInterceptor),
	)

	server := api.Server{}
	server.InitTest()
	pb.RegisterProductInfoServer(s, &server)
	pb.RegisterOrderManagementServer(s, &server)
	log.Println("Starting gRPC listener on port " + port)
	if err := s.Serve(lis); err != nil {
		log.Fatalf("failed to serve: %v", err)
	}
}
